import os
import socket
import subprocess
import traceback
from tkinter import Tk
from tkinter import filedialog
from tkinter import messagebox


# @tip 文件传输，在局域网内共享你电脑的某个目录
class Main:

    def __init__(self):
        port = '80'
        root = Tk()
        # 隐藏主窗口
        root.withdraw()
        is_start = messagebox.askyesno('文件共享', '是否选择目录进行共享？')
        if not is_start:
            root.destroy()
            return
        # 获取共享文件目录路径
        path = filedialog.askdirectory()
        if not path:
            root.destroy()
            return
        os.chdir(path)
        self.start(port)

    def start(self, port):
        child = None
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            sock.connect(('8.8.8.8', 80))
            ip = sock.getsockname()[0]
            sock.close()
            child = subprocess.Popen('py -m http.server ' + port)
            messagebox.showinfo('文件共享', '开启文件共享中\n请在浏览器中访问: http://%s\n如需关闭请点击按钮' % ip)
        except:
            print(traceback.format_exc())
        finally:
            child.terminate()
